package com.ruoyi.app.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.drake.net.Get
import com.drake.net.Post
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.hjq.toast.ToastUtils
import com.ruoyi.app.MainActivity
import com.ruoyi.app.R
import com.ruoyi.app.api.ConfigApi
import com.ruoyi.app.api.OKHttpUtils
import com.ruoyi.app.databinding.ActivityLoginBinding
import com.ruoyi.app.model.entity.CaptchaImageEntity
import com.ruoyi.app.model.entity.LoginEntity
import com.ruoyi.app.model.request.LoginRequest
import com.ruoyi.code.Frame
import com.ruoyi.code.base.BaseBindingActivity
import com.ruoyi.code.witget.toast
import com.tencent.mmkv.MMKV
import com.xuexiang.xupdate.XUpdate
import com.zackratos.ultimatebarx.ultimatebarx.navigationBar
import com.zackratos.ultimatebarx.ultimatebarx.statusBar


class LoginActivity : BaseBindingActivity<ActivityLoginBinding>() {

    companion object {
        fun startActivity(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

    private var uuid: String? = ""
    private var isRegister = false

    override fun initView() {
        statusBar {
            fitWindow = true
            light = true
            colorRes = R.color.white
        }

        navigationBar {
            fitWindow = true
            colorRes = R.color.white
        }

        binding.btnLogin.setOnClickListener {
            val code = binding.etCode.text.toString().trim()
            if (binding.llCaptchaImage.visibility == View.VISIBLE) {
                if (TextUtils.isEmpty(code)) {
                    toast("请输入验证码")
                    return@setOnClickListener
                }
            }
            val username = binding.etAccount.text.toString().trim()
            if (TextUtils.isEmpty(username)) {
                toast("请输入账号")
                return@setOnClickListener
            }

            val password = binding.etPassword.text.toString().trim()
            if (TextUtils.isEmpty(password)) {
                toast("请输入密码")
                return@setOnClickListener
            }
            scopeDialog {
                val data = Post<LoginEntity>(ConfigApi.login) {
                    body = OKHttpUtils.getRequestBody(
                        LoginRequest(
                            code,
                            password,
                            username,
                            uuid ?: ""
                        )
                    )
                }.await()
                if (data.code == ConfigApi.SUCESSS) {
                    MMKV.defaultMMKV().encode("token", data.token)
                    MainActivity.startActivity(this@LoginActivity)
                    finish()
                } else {
                    ToastUtils.show(data.msg)
                    getVerificationCode()
                }
            }.catch {
                ToastUtils.show(it.message)
                getVerificationCode()
            }
        }

        binding.logoCodeImage.setOnClickListener {
            getVerificationCode()
        }

        binding.tvProtocol.setOnClickListener {
            WebActivity.startActivity(this, "用户协议", ConfigApi.baseUrl + "/protocol.html")
        }
        binding.tvPrivacy.setOnClickListener {
            WebActivity.startActivity(this, "隐私政策", ConfigApi.baseUrl + "/protocol.html")
        }
        binding.tvRegister.setOnClickListener {
            RegisterActivity.startActivity(this)
        }

        val token = MMKV.defaultMMKV().decodeString("token")
        if (!token.isNullOrEmpty()) {
            MainActivity.startActivity(this)
            finish()
            return
        }

    }

    override fun initData() {
        if (isRegister) {
            binding.llRegister.visibility = View.VISIBLE
        } else {
            binding.llRegister.visibility = View.GONE
        }
        getVerificationCode()
        XUpdate.newBuild(this)
            .promptThemeColor(ContextCompat.getColor(this, R.color.red))
            .updateUrl(ConfigApi.uploadApp)
            .update()
    }

    private fun getVerificationCode() {
        scopeNetLife {
            val data = Get<CaptchaImageEntity>(ConfigApi.getCaptchaImage).await()
            if (data.code == ConfigApi.SUCESSS) {
                val captchaEnabled = data.captchaEnabled
                if (captchaEnabled) {
                    binding.llCaptchaImage.visibility = View.VISIBLE
                    uuid = data.uuid
                    Glide.with(Frame.getContext())
                        .load("data:image/gif;base64,${data.img}")
                        .into(binding.logoCodeImage)
                } else {
                    binding.llCaptchaImage.visibility = View.GONE
                }
            } else {
                toast(data.msg)
            }
        }
    }

}
